<template>
  <!-- 预收款 -->
  <div class="mainWrap">
    <el-row :gutter="20" class="container">
      <el-col class="left" :span="6">
        <BreakSpace label="新增预收款" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <FormPanel ref="formPanel" :list="formList" :cols="1" :labelWidth="90" :isSubmitBtn="false"></FormPanel>
        <!--操作 -->
        <div :style="{ paddingTop: '15px', paddingLeft: '10px' }">
          <AjaxButton type="primary" :disabled="!saveable" :click="saveAdvancesReceived">保存</AjaxButton>
          <!-- <el-button type="primary" @click="printClick">打印</el-button> -->
          <el-button type="primary" @click="closeClick">取消</el-button>
        </div>
      </el-col>

      <el-col class="right" :span="18">
        <BreakSpace label="预收款查询" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <TopFilter ref="topFilter" :list="topFilterList" :cols="4" labelWidth="85" @filterChange="changeHandle"></TopFilter>
        <BreakSpace label="客户信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <FilterTable
          ref="table"
          columnsRef="repair-advancesReceived-Ref"
          selectionType="single"
          :columns="columns"
          height="200"
          :fetchapi="fetchapi"
          :params="fetchParams"
          :datakey="'rows'"
          :onColumnsChange="columns => (this.columns = columns)"
          :onEnterEvent="tableDbclickFun"
        >
          <template slot="controls">
            <AjaxButton size="small" type="primary" :click="exportClick">导出客户信息</AjaxButton>
          </template>
        </FilterTable>
        <BreakSpace label="预收款明细" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <FilterTable
          ref="table"
          columnsRef="repair-advancesReceived-detail-Ref"
          :isSelectColumn="false"
          :columns="detailColumns"
          height="200"
          :dataSource="detailDataSource"
          :datakey="'rows'"
          :isMemoryPagination="true"
          :onColumnsChange="columns => (this.detailColumns = columns)"
          :onSyncTableData="tableChangeFun"
        >
          <template slot="controls">
            <AjaxButton size="small" type="primary" :disabled="exportDetailBtnDisabele" :click="exportDetailClick">导出预收款明细</AjaxButton>
          </template>
        </FilterTable>
      </el-col>
    </el-row>
    <BaseDialog :visible.sync="action.visible" title="选择客户" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <customerModal :type="action.type" :customerCode="formList[1].initialValue" @close="closeHandler" @change="getCustomerInfo" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import { exportOwnerExcel, saveAdvancesReceived, findOwnerAmount, findOwnerAmountDetail, exportOwnerAmountDetail } from '@/api/repair/repairFinance/index.js';
import { getUserId, getUser } from '@/assets/js/auth';
import customerModal from './customerModal';
import moment from 'moment';

export default {
  name: 'repair-advancesReceived',
  components: {
    customerModal
  },
  mixins: [dictionary],
  data() {
    return {
      formList: this.createFormList(),
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchapi: findOwnerAmount,
      detailColumns: this.createDetailTableColumns(),
      fetchParams: { xhrAbort: true },
      detailDataSource: [],
      action: { type: '', title: '', visible: false, data: {} },
      selectRow: {},
      saveable: true,
      exportDetailBtnDisabele: false
    };
  },
  methods: {
    async exportDetailClick() {
      let res = await exportOwnerAmountDetail({ ownerNo: this.selectRow.ownerNo, receiveType: this.selectRow.receiveType });
      console.log(res);
      exportExcelFile(res.data, '预收款明细');
    },
    async exportClick() {
      const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
      let res = await exportOwnerExcel(data);
      console.log(res);
      exportExcelFile(res.data, '客户信息');
    },
    async findOwnerAmountDetail(params) {
      let res = await findOwnerAmountDetail(params);
      if (res.resultCode == 200) {
        this.detailDataSource = res.data;
      }
    },
    tableChangeFun(details) {
      if (details && details.length) {
        this.exportDetailBtnDisabele = false;
      } else {
        this.exportDetailBtnDisabele = true;
      }
    },
    async tableDbclickFun(val) {
      // 清空上一次的值
      // const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
      this.detailDataSource = [];
      this.selectRow = val;
      console.log(val);
      this.findOwnerAmountDetail({ ownerNo: val.ownerNo, receiveType: val.receiveType });
    },
    selectCustomer() {
      this.action.visible = true;
    },
    async getCustomerInfo(val) {
      // this.dataSource1 = [];
      this.action.visible = false;
      this.formList.find(item => item.fieldName === 'ownerNo').initialValue = val[0].ownerNo;
      this.formList.find(item => item.fieldName === 'ownerName').initialValue = val[0].ownerName;
      this.formList.find(item => item.fieldName === 'prePayCusType').initialValue = val[0].ownerProperty;
      console.log(val, '选择客户');
    },
    printClick() {},
    closeClick() {
      // 允许保存
      this.saveable = true;
      // 重置数据
      this.$refs.formPanel.RESET_FORM();
      // 重置状态
      let data = this.createFormList();
      this.formList.forEach((element, index) => {
        if (Object.hasOwnProperty.call(data[index], 'disabled')) {
          element.disabled = data[index].disabled;
        } else {
          element.disabled = false;
        }
      });
      // this.formList.find(item => item.fieldName === 'preReceiveNo').disabled = true;
      // this.formList.find(item => item.fieldName === 'ownerNo').disabled = false;
      // this.formList.find(item => item.fieldName === 'ownerName').disabled = true;
      // this.formList.find(item => item.fieldName === 'receiveType').disabled = false;
      // this.formList.find(item => item.fieldName === 'payTypeCode').disabled = false;
      // this.formList.find(item => item.fieldName === 'receiveAmount').disabled = false;
      // this.formList.find(item => item.fieldName === 'checkNo').disabled = false;
      // this.formList.find(item => item.fieldName === 'invoiceTypeCode').disabled = false;
      // this.formList.find(item => item.fieldName === 'billNo').disabled = false;
      // this.formList.find(item => item.fieldName === 'handler').disabled = true;
      // this.formList.find(item => item.fieldName === 'remark').disabled = true;
      // this.formList.find(item => item.fieldName === 'prePayCusType').disabled = true;
    },
    async saveAdvancesReceived() {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      if (this.formList.find(item => item.fieldName === 'receiveAmount').initialValue === 0) {
        this.$notify.error({ title: '提示信息', message: '收款金额不能是0！！！' });
        return;
      }
      let res = await saveAdvancesReceived(data);
      console.log(res);
      if (res.resultCode == 200) {
        this.formList.find(x => x.fieldName === 'preReceiveNo').initialValue = res.data;
        this.$notify.success({ title: '提示信息', message: '保存成功' });
        this.formList.forEach(element => {
          element.disabled = true;
        });
        this.saveable = false;
      }
    },

    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '收款单号',
          fieldName: 'preReceiveNo',
          // placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'ownerNo',
          // placeholder: '请输入...',
          rules: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectCustomer(props)}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'ownerName',
          // placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '收款类别',
          fieldName: 'receiveType',
          placeholder: '请选择...',
          initialValue: 99991001,
          itemList: this.createDictList('9999'),
          rules: [{ required: true, message: '请选择', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '付款方式',
          fieldName: 'payTypeCode',
          placeholder: '请选择...',
          itemList: this.createDictList('8044').filter(x => x.value != 80441010 && x.value != 80441011), // 去掉二维码支付和直属平台
          rules: [{ required: true, message: '请选择', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '收款金额',
          precision: 2,
          min: -Infinity,
          fieldName: 'receiveAmount',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请填写收款金额', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '支票号码',
          fieldName: 'checkNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '发票类型',
          fieldName: 'invoiceTypeCode',
          placeholder: '请选择...',
          itemList: this.createDictList('1111')
        },
        {
          type: 'INPUT',
          label: '票据号码',
          fieldName: 'billNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '经手人',
          fieldName: 'handler',
          placeholder: '请输入...',
          disabled: true,
          initialValue: getUserId(),
          itemList: [{ text: getUser(), value: getUserId() }]
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'prePayCusType',
          placeholder: '请选择...',
          disabled: true,
          itemList: this.createDictList('8011')
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'ownerNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'ownerName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '收款类别',
          fieldName: 'receiveType',
          placeholder: '请输入...',
          disabled: false,
          // initialValue: 99991001,
          itemList: this.createDictList('9999')
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 100,
        //   // fixed: 'left',
        //   render: (props, h) => {
        //     return (
        //       <div>
        //         <el-button size="mini" type="text" icon="el-icon-document" onClick={() => this.queryDetail(props.row)}>
        //           明细
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },

        {
          title: '客户编号',
          dataIndex: 'ownerNo',
          filter: true,
          filterType: 'input',
          width: 160
        },
        {
          title: '客户名称',
          dataIndex: 'ownerName',
          filter: true,
          filterType: 'input'
        },
        {
          title: '地址',
          dataIndex: 'address',
          filter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '邮编',
          dataIndex: 'zipCode',
          filter: true,
          filterType: 'input'
        },
        {
          title: '电话',
          dataIndex: 'phone',
          filter: true,
          filterType: 'input',
          width: 160
        },
        {
          title: '手机',
          dataIndex: 'mobile',
          filter: true,
          filterType: 'input',
          width: 160
        },
        {
          title: '收款金额',
          dataIndex: 'receiveAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        }
      ];
    },
    createDetailTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '单据号码',
          dataIndex: 'preReceiveNo',
          filter: true,
          filterType: 'input',
          width: 160
        },
        {
          title: '发生时间',
          dataIndex: 'handleTime',
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          width: 160
        },
        {
          title: '收款类别',
          dataIndex: 'receiveType',
          filter: true,
          filterType: 'input',
          dictItems: this.createDictList('9999')
        },
        {
          title: '经手人',
          dataIndex: 'handlerName',
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户编号',
          dataIndex: 'ownerNo',
          filter: true,
          filterType: 'input',
          width: 160
        },
        {
          title: '客户名称',
          dataIndex: 'ownerName',
          filter: true,
          filterType: 'input'
        },
        {
          title: '收款金额',
          dataIndex: 'receiveAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '本次支出',
          dataIndex: 'payoutAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '本次结余',
          dataIndex: 'afterAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '付款方式',
          dataIndex: 'payTypeCode',
          filter: true,
          filterType: 'input',
          dictItems: this.createDictList('8044')
        },
        {
          title: '支票号码',
          dataIndex: 'checkNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '发票号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票类型',
          dataIndex: 'invoiceTypeCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          dictItems: this.createDictList('1111')
        }
      ];
    },
    closeHandler(val, type) {
      this.action.visible = val;
      if (type === 'refresh') {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
      this.detailDataSource = []; // 重新搜索清空明细
    },
    exportExcelReceiveData() {
      exportExcelData(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res, '预收款明细导出');
      });
    }
  }
};
</script>
<style lang="less" scoped>
.mainWrap {
  padding-bottom: @modulePadding;
  .container {
    margin-top: 10px;
    .left {
      border-radius: @borderRadius;
      padding: @modulePadding;
      background: #fff;
      height: 100%;
    }
    .right {
      background: #fff;
      border-radius: @borderRadius;
      padding: @modulePadding;
      border-left: 10px solid #f2f4f8;
    }
  }
}
</style>
